import React, { useState, useCallback, useRef, useEffect } from 'react'
import { Form, Input, Modal, message, Select } from 'antd'
import http from '@/utils/request'
import type { orderType } from '@/types'

interface IniviteOrderProps {
  isOpen: boolean;
  order?: orderType;
  success: () => void;
  close: () => void;
  type?: 'Fail' | 'Batch-invite';
}

interface UserOption {
  value: string;
  label: string;
}

interface UserData {
  userCode: string;
  userName: string;
}

const IniviteOrder: React.FC<IniviteOrderProps> = ({ isOpen, order, success, close, type }) => {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [userOptions, setUserOptions] = useState<UserOption[]>([])
  const [userLoading, setUserLoading] = useState(false)
  const timerRef = useRef<NodeJS.Timeout>()

  const fetchUsers = useCallback(async (keyword = '') => {
    try {
      setUserLoading(true)
      const res = await http.get('/disp/sys/user/listEnableUser', {
        params: { keyword }
      })
      const options = (res?.data || []).map((user: UserData) => ({
        value: user.userCode,
        label: user.userName
      }))
      setUserOptions(options)
    } catch (error) {
      console.error('获取用户列表失败:', error)
    } finally {
      setUserLoading(false)
    }
  }, [])

  useEffect(() => {
    if (isOpen && type !== 'Fail') {
      fetchUsers()
    }
  }, [isOpen, fetchUsers, type])

  const handleSearch = useCallback((value: string) => {
    if (timerRef.current) {
      clearTimeout(timerRef.current)
    }
    timerRef.current = setTimeout(() => {
      fetchUsers(value)
    }, 500)
  }, [fetchUsers])

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      setLoading(true)
      if (type === 'Fail') {
        await http.post('/disp/biz/order/invitationFailOrder', {
          id: order?.id,
          orderComment: values.orderComment
        })
        message.success('邀约失败处理成功')
      } else if (type === 'Batch-invite') {
        const orderIds = String(order?.id || '').split(',')
        await http.post('/disp/biz/order/batchAssignInvitationUser', {
          orderIds,
          userCode: values.userCode,
          orderComment: values.orderComment
        })
        message.success('批量邀约成功')
      } else {
        await http.post('/disp/biz/order/assignInvitationUser', {
          id: order?.id,
          ...values
        })
        message.success('邀约成功')
      }
      success()
      form.resetFields()
    } catch (error) {
      const msg = error?.msg as string
      message.error(msg || '操作失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Modal
      title={type === 'Fail' ? '邀约失败' : (type === 'Batch-invite' ? '批量邀约' : '邀约订单')}
      open={isOpen}
      onOk={handleSubmit}
      onCancel={close}
      confirmLoading={loading}
      destroyOnHidden
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{ id: order?.id }}
      >
        {type !== 'Fail' && (
          <Form.Item
            name="userCode"
            label="选择用户"
            rules={[{ required: true, message: '请选择用户' }]}
          >
            <Select
              showSearch
              placeholder="请输入用户名搜索"
              loading={userLoading}
              options={userOptions}
              onSearch={handleSearch}
              filterOption={false}
              notFoundContent={userLoading ? '加载中...' : '未找到用户'}
            />
          </Form.Item>
        )}
        <Form.Item
          name="orderComment"
          label="邀约备注"
          rules={[{ required: true, message: '请输入邀约备注' }]}
        >
          <Input.TextArea
            rows={4}
            placeholder="请输入邀约备注"
            maxLength={200}
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default IniviteOrder